import { ActionSheetButton, actionSheetController, ActionSheetOptions } from '@ionic/vue';
import {
  IAppActionSheetButton,
  IAppActionSheetService,
  ICtrlActionResult,
  IAppActionSheetOptions,
  IParam,
} from 'ibz-core';

/**
 * 动作面板服务
 *
 * @class AppActionSheetService
 * @description 底部弹出的模态面板
 */
export class AppActionSheetService implements IAppActionSheetService {
  /**
   * @description 动态面板服务实例对象（单例）
   * @protected
   * @static
   * @type {AppActionSheetService}
   * @memberof AppActionSheetService
   */
  protected static instance: AppActionSheetService;

  /**
   * @description 获取动态面板服务实例对象
   * @static
   * @return {*}  {IAppActionSheetService}
   * @memberof AppActionSheetService
   */
  public static getInstance(): IAppActionSheetService {
    if (!this.instance) {
      this.instance = new AppActionSheetService();
    }
    return this.instance;
  }

  /**
   * @description 创建动态面板
   * @param {IAppActionSheetOptions} options 动态面板配置
   * @return {*}  {Promise<ICtrlActionResult>}
   * @memberof AppActionSheetService
   */
  async create(options: IAppActionSheetOptions): Promise<ICtrlActionResult> {
    try {
      const ionicASOptions = this.configConvert(options) as ActionSheetOptions;
      const actionSheet = await actionSheetController.create(ionicASOptions);
      await actionSheet.present();
      return { ret: true, data: [] };
    } catch (error: any) {
      return { ret: false, data: [error] };
    }
  }

  /**
   * @description 配置转换
   * @private
   * @param {IAppActionSheetOptions} options 动态面板配置
   * @return {*}  {IParam}
   * @memberof AppActionSheetService
   */
  private configConvert(options: IAppActionSheetOptions): IParam {
    const convertOptions: ActionSheetOptions = {
      id: options.id,
      header: options.header,
      subHeader: options.subHeader,
      cssClass: options.cssClass,
      buttons: [],
      backdropDismiss: options.backdropDismiss,
      translucent: options.translucent,
    };
    options.buttons.forEach((button: IAppActionSheetButton) => {
      const ionicASButton: ActionSheetButton = {
        text: button.text,
        role: button.role,
        icon: button.icon,
        cssClass: button.cssClass,
        handler: () => {
          button.handler();
        },
      };
      convertOptions.buttons.push(ionicASButton);
    });
    return convertOptions;
  }
}
